package com.itheima.service.impl;

import com.itheima.mapper.ItemCategoryMapper;
import com.itheima.pojo.ItemCategory;
import com.itheima.service.ItemCategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class ItemCategoryServiceImpl implements ItemCategoryService {
    
    private final ItemCategoryMapper itemCategoryMapper;

    @Override
    public List<ItemCategory> list() {
        // 查询所有分类
        List<ItemCategory> list = itemCategoryMapper.list();
        
        // 找到所有顶级分类
        List<ItemCategory> parents = list.stream()
                .filter(c -> c.getParentId() == 0)
                .collect(Collectors.toList());
        
        // 找到所有非顶级分类
        List<ItemCategory> children = list.stream()
                .filter(c -> c.getParentId() > 0)
                .collect(Collectors.toList());
        
        // 递归查找子分类
        parents.forEach(c -> findChildren(c, children));
        
        return parents;
    }
    
    @Override
    public List<ItemCategory> listAll() {
        return itemCategoryMapper.list();
    }
    
    @Override
    public ItemCategory getById(Integer id) {
        return itemCategoryMapper.getById(id);
    }
    
    @Override
    public void save(ItemCategory category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setIsDel(1);
        itemCategoryMapper.insert(category);
    }
    
    @Override
    public void update(ItemCategory category) {
        category.setUpdateTime(LocalDateTime.now());
        itemCategoryMapper.update(category);
    }
    
    @Override
    public void deleteById(Integer id) {
        itemCategoryMapper.deleteById(id);
    }
    
    /***
     * 递归查找子分类
     */
    private void findChildren(ItemCategory category, List<ItemCategory> children) {
        // 循环所有子分类,判断查找当前类的子分类
        List<ItemCategory> list = children.stream()
                .filter(c -> Objects.equals(c.getParentId(), category.getId()))
                .collect(Collectors.toList());
        
        // 如果没有子分类，则结束，有就继续查找（递归查找）
        list.forEach(c -> findChildren(c, children));
        
        // 将查找的结果赋值给当前类的子分类属性children
        category.setChildren(list);
    }
}